from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from user.models import User
from goods.models import Goods
from functools import reduce
from rest_framework.pagination import PageNumberPagination
from rest_framework.generics import ListAPIView
from rest_framework_jwt.utils import jwt_decode_handler
import redis

# Create your views here.
# 添加购物车
class AddCart(APIView):
    def post(self,request):
         dict_user = request.data.get('user')
         productID = request.data.get('productID')
         try:
             user = User.objects.get(username=dict_user)
         except Exception as e:
             return Response({'msg':"用户不存在","code":204})
         try:
             goods = Goods.objects.get(id=productID)
         except Exception as e:
             return Response({'msg':"商品不存在","code":400})
         rdb = redis.Redis(password='123456')
         cart_key = 'cart_%s'%user.id
         cart_selected = 'cart_selected_%s'%user.id
         count = 1
         if goods.stock > 0:
             num = rdb.hget(cart_key,goods.id)
             if num:
                 goods_count = int(num.decode())
                 if goods_count > goods.stock:
                     return Response({'msg':'已经超出限购数量',"code":202})
                 if goods_count <= goods.stock:
                     rdb.hset(cart_key,goods.id,count)
                     rdb.sadd(cart_selected,goods.id)
                     rdb.close()
                     return Response({'msg':"商品已存在,数量+1","code":201})
             else:
                 rdb.hset(cart_key, goods.id, count)
                 rdb.sadd(cart_selected, goods.id)
                 rdb.close()
                 shopping_cart_data = {
                     "id": cart_key,
                     "productID": goods.id,
                     "productName": goods.sku_name,
                     "productImg": goods.img,
                     "price": goods.selling_price,
                     "num": count,  # 该商品在购物车中的数量
                     "maxNum": goods.stock,  # 限购数量
                     "check": True,  # 加购，默认是勾选状态
                 }
                 return Response({'msg': "添加购物车成功", "code": 200, "shoppingCart": shopping_cart_data})
         else:
             return Response({"code": 203, "msg": "库存不足，无法购买！"})

# 获取购物车
class CartInfo(APIView):
    def post(self,request):
        user_name = request.data.get('user').get('userName')
        try:
            user = User.objects.get(username=user_name)
        except Exception as e:
            return Response({'msg':'此用户不存在',"code":204})
        cart_key = 'cart_%s' % user.id
        cart_selected = 'cart_selected_%s' % user.id
        rdb = redis.Redis(password='123456')
        selected_gid = [int(i.decode()) for i in rdb.smembers(cart_selected)]
        shopping_cart_data = []
        for gid,g_count in rdb.hgetall(cart_key).items():
            gid = int(gid.decode())
            g_count = int(g_count.decode())
            if gid in selected_gid:
                good = Goods.objects.get(id=gid)
                shopping_cart_data.append({
                    "id": cart_key,
                    "productID": good.id,
                    "productName": good.sku_name,
                    "productImg": good.img,
                    "price": good.selling_price,
                    "num": g_count,  # 该商品在购物车中的数量
                    "maxNum": good.stock,  # 限购数量
                    "check": True,  # 加购，默认是勾选状态
                })
            else:
                good = Goods.objects.get(id=gid)
                shopping_cart_data.append({
                    "id": cart_key,
                    "productID": good.id,
                    "productName": good.sku_name,
                    "productImg": good.img,
                    "price": good.selling_price,
                    "num": g_count,  # 该商品在购物车中的数量
                    "maxNum": good.stock,  # 限购数量
                    "check": False,  # 加购，默认是勾选状态
                })
        return Response({"msg":"获取用户的购物车数据成功","code":200,"shoppingCartData":shopping_cart_data})

# 更新购物车商品数量
class UpdateCartNum(APIView):
    def post(self,request):
        user_name = request.data.get('user').get('userName')
        pid =  request.data.get('productID')
        good_num = request.data.get('num')
        try:
            user = User.objects.get(username=user_name)
        except Exception as e:
            return Response({'msg': '此用户不存在', "code": 204})
        cart_key = 'cart_%s' % user.id
        cart_selected = 'cart_selected_%s' % user.id
        rdb = redis.Redis(password='123456')
        try:
            rdb.sadd(cart_selected,pid)
            rdb.hset(cart_key,pid,good_num)
            rdb.close()
            return Response({'msg':'更新商品数量成功',"code":200})
        except:
            return Response({'msg':'更新商品数量失败','code':400})

# 更新购物车商品状态
class UpdateCarStatus(APIView):
    def get(self,request):
        gid = request.query_params.get('productID')
        cart_key = request.query_params.get('cartID')
        status = request.query_params.get('val')
        cart_selected = 'cart_selected_%s'%cart_key.split('_')[-1]
        rdb = redis.Redis(password='123456')
        if status == 'true':
            rdb.sadd(cart_selected,gid)
        else:
            rdb.srem(cart_selected,gid)
        rdb.close()
        return Response({'msg':'修改状态成功','code':200})

# 购物车全选
class UpdateAllstatus(APIView):
    def post(self,request):
        cart_key = request.data.get('cartID')
        status = request.data.get('val')
        cart_selected = "cart_selected_%s" % cart_key.split('_')[-1]
        rdb = redis.Redis(password='123456')
        if status == "true":
            goods = rdb.hkeys(cart_key)
            rdb.sadd(cart_selected, *goods)
        else:
            rdb.delete(cart_selected)
        return Response({"msg": "修改状态成功", "code": 200})

# 删除购物车中商品
class DeleteCart(APIView):
    def post(self,request):
        user_name = request.data.get('user').get('userName')
        pid = request.data.get('productID')
        try:
            user = User.objects.get(username=user_name)
        except Exception as e:
            return Response({'msg': '此用户不存在', "code": 204})
        cart_key = "cart_%s" % user.id
        cart_selected = "cart_selected_%s" % user.id
        rdb = redis.Redis(password='123456')
        try:
            rdb.hdel(cart_key, pid)
            rdb.srem(cart_selected, pid)
            rdb.close()
        except Exception as e:
            return Response({'msg': "删除购物车失败", "code": 400})
        return Response({'msg': "删除购物车成功", "code": 200})